<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\plus\agent\Setting;
use app\api\model\user\RegisterInfo as RegisterInfoModel;
use app\api\model\user\User as UserModel;
use app\api\model\order\Order as OrderModel;
use app\api\model\settings\Setting as SettingModel;
use app\api\model\plus\coupon\UserCoupon as UserCouponModel;
use app\common\enum\settings\GetPhoneTypeEnum;
use app\common\exception\BaseException;
use app\common\model\car\Car;
use app\common\model\driver\Driver;
use app\common\model\driver\MyDriver;
use app\common\model\order\RechargeOrder;
use app\common\model\user\BankCard;
use app\common\model\user\UserWithdrawal;
use think\facade\Cache;
use app\api\model\supplier\Supplier as SupplierModel;
use app\common\enum\order\OrderPayTypeEnum;
use think\facade\Db;
/**
 * 个人中心主页
 */
class Index extends Controller
{
    /**
     * 获取当前用户信息
     */
    public function detail($source = 'wx')
    {
        // 当前用户信息
        $user = $this->getUser();
        //店铺信息
        $user['is_recycle'] = $user['supplierUser']?SupplierModel::detail($user['supplierUser']['shop_supplier_id'])['is_recycle']:'';
        $coupon_model = new UserCouponModel();
        $coupon = count($coupon_model->getList($user['user_id'], -1, false, false));
        // 订单总数
        $model = new OrderModel;

        // 分销商基本设置
        $setting = Setting::getItem('basic');
        // 是否开启分销功能
        $agent_open = $setting['is_open'];
        //商城设置
        $store = SettingModel::getItem('store');
        //供应商入住背景图
        $supplier_image = isset($store['supplier_image'])?$store['supplier_image']:'';
        return $this->renderSuccess('', [
            'coupon' => $coupon,
            'userInfo' => $user,
            'orderCount' => [
                'payment' => $model->getCount($user, 'payment'),
                'received' => $model->getCount($user, 'received'),
                'comment' => $model->getCount($user, 'comment'),
            ],
            'setting' => [
                'points_name' => SettingModel::getPointsName(),
                'agent_open' => $agent_open,
                'supplier_image' => $supplier_image
            ],
            'sign' => SettingModel::getItem('sign'),
            'getPhone' => $this->isGetPhone(),
            'menus' => UserModel::getMenus($user, $source)   // 个人中心菜单列表
        ]);
    }

    /**
     * 当前用户设置
     */
    public function setting()
    {
        // 当前用户信息
        $user = $this->getUser();

        return $this->renderSuccess('', [
            'userInfo' => $user
        ]);
    }

    private function isGetPhone(){
        $user = $this->getUser();
        if($user['mobile'] != ''){
            return false;
        }
        $settings = SettingModel::getItem('getPhone');
        if(in_array(GetPhoneTypeEnum::USER, $settings['area_type'])){
            // 缓存时间
            $key = 'get_phone_' . $user['user_id'];
            if (!$data = Cache::get($key)) {
                $settings['send_day'] > 0 && Cache::set($key, '1', 86400 * $settings['send_day']);
                return true;
            }
        }
        return false;
    }
    //我的车辆
    public function my_car(){
        // 当前用户信息
        $user = $this->getUser();
        $where = array(
            'a.user_id' => $user['user_id'],
            'a.category' => 1,
            'a.is_delete'=>0
        );
        $carlist = Db::name('car')
                ->alias('a')
                ->field('a.*,b.type_name,c.realname as drivername')
                ->join('jjjshop_car_type b','a.car_type = b.type_id','LEFT')
                ->join('jjjshop_my_driver c','a.driver_id = c.id','LEFT')
                ->where($where)
                ->order('a.create_time desc')
                ->select();
        return $this->renderSuccess('', [
            'userInfo' => $user,
            'car'      => $carlist
        ]);
    }
    //二手车
    public function user_car(){
        // 当前用户信息
        $user = $this->getUser();
        $type = $this->request->param("type");
        if($type){
            $where = array(
                'a.category' => 2,
                'a.is_delete'=>0,
                'a.status'=>1,
            );
        }else{
            $where = array(
                'a.category' => 2,
                'a.user_id'=>$user['user_id'],
                'a.is_delete'=>0
            );
        }

        $carlist = Db::name('car')
                ->alias('a')
                ->field('a.*,b.type_name')
                ->join('jjjshop_car_type b','a.car_type = b.type_id','LEFT')
                ->where($where)
                ->order('a.create_time desc')
                ->select();
        return $this->renderSuccess('', [
            'userInfo' => $user,
            'car'      => $carlist
        ]);
    }
    //我的司机
    public function my_driver()
    {
        // 当前用户信息
        $user = $this->getUser();
        $model = new MyDriver();
        $where = array('user_id' => $user['user_id']);
        $carlist = $model->get_list($where);

        return $this->renderSuccess('获取成功', [
            'userInfo' => $user,
            'driver'   => $carlist
        ]);
    }

    //删除司机
    public function del_mydriver()
    {
        $id = $this->request->param('id');
        $model = new MyDriver();
        $res = $model->del($id);
        if($res){
            return $this->renderSuccess('操作成功！');
        }else{
            return $this->renderError('操作失败！');
        }
    }

    //用户银行卡
    public function bankCard()
    {
        $user = $this->getUser();
        $where = array('user_id' => $user['user_id'],'is_delete'=>0);
        $bank = Db::name('user_bank')->where($where)->select()->toArray();

        return $this->renderSuccess('', [
            //'userInfo' => $user,
            'bank'     => $bank
        ]);
    }
    //添加银行卡
    public function add_bankcard()
    {
        $data = $this->request->param();
        $user = $this->getUser();
        $data['user_id'] = $user['user_id'];
        $model = new BankCard();
        $res = $model->addCard($data);
        if($res){
            return $this->renderSuccess('操作成功！');
        }else{
            return $this->renderError($model->getError());
        }

    }
    //编辑银行卡
    public function edit_bankcard()
    {
        $data = $this->request->param();
        $user = $this->getUser();
        $data['user_id'] = $user['user_id'];
        $model = new BankCard();
        $res = $model->editCard($data);
        if($res){
            return $this->renderSuccess('操作成功！');
        }else{
            return $this->renderError($model->getError());
        }
    }
    //银行卡详情
    public function bankcard_detail()
    {
        $id = $this->request->param('id');
        $model = new BankCard();
        $res = $model->where(array('id'=>$id))->find();
        return $this->renderSuccess('操作成功！',['info'=>$res]);
    }
    //删除银行卡
    public function del_bankcard()
    {
        $id = $this->request->param('id');
        $model = new BankCard();
        $res = $model->where(array('id'=>$id))->update(array('is_delete'=>1));
        if($res){
            return $this->renderSuccess('操作成功！');
        }else{
            return $this->renderError('操作失败！');
        }
    }

    public function vip()
    {
        $user = $this->getUser();
        $where = array();
        $vip = Db::name('user_grade')->where($where)->select();
        $data = [];
        foreach ($vip as $v) {
            $list = [];
            $list['vip_combo']     = $v['name'];
            $list['vip_privilege'] = $v['remark'];
            $list['vip_endtime']   = date('Y-m-d H:i:s',$v['create_time']);
            $list['vip_begintime'] = date('Y-m-d H:i:s',$v['create_time']);
            $list['vip_id']        = $v['grade_id'];
            $data[] = $list;
        }
        return $this->renderSuccess('', [
            'userInfo' => $user,
            'vip'      => $data
        ]);
    }
    //招聘司机
    public function driver()
    {
        $user = $this->getUser();
        $data = $this->request->post();
        $model = new Driver();
        $carlist = $model->shop_list($data);

        return $this->renderSuccess('', [
            'userInfo' => $user,
            'driver'   => $carlist
        ]);
    }

    public function my_driver_detail()
    {
        $id = $this->request->param('id');
        $model = new Driver();
        $info = $model->get_detail($id);
        return $this->renderSuccess('', [
            'info' => $info
        ]);
    }
    //添加招聘司机
    public function add_recruit_driver()
    {
        $data = $this->request->post();
        $user = $this->getUser();
        $data['user_id'] = $user['user_id'];
        $model = new Driver();
        if($model->add($data,$user)){
            return $this->renderSuccess('提交成功');
        }else{
            return $this->renderError('网络似乎开小差了');
        }

    }
    //招聘司机
    public function recruit_driver()
    {
        $user = $this->getUser();
        $model = new Driver();
        $info = $model->alias('d')
            ->field('d.*,da.driver_age as age_name,dt.type_name')
            ->join('jjjshop_driver_age da','d.driver_age=da.id','left')
            ->join('jjjshop_driver_type dt','d.driver_type=dt.type_id','left')
            ->where(array('user_id'=>$user['user_id']))->find();

        return $this->renderSuccess('获取成功', [
            'Info' => $info,
        ]);

    }

    public function updateinfo()
    {
        $u    = $this->getUser();
        $data = $this->request->post();
        $user = Db::name('user')->where("user_id = ".$u['user_id'])->find();
        if(empty($user)){
            return $this->renderError('未找到该用户');
        }
        $save = array(
            'avatarUrl' => $data['updateinfo_portrait'],
            'mobile'    => $data['updateinfo_phone']
        );
        $res = Db::name('user')->where("user_id = ".$u['user_id'])->update($save);
        if($res){
            return $this->renderSuccess('修改成功');
        }else{
            return $this->renderError('网络似乎开小差了');
        }
    }
    public function my_money()
    {
        $user = $this->getUser();
        $list = array(
            'balance' => $user['balance'],
            'yesterdayEarnings' => 0,
            'thisEarnings' => 0,
            'integral' => $user['points'],
        );
        return $this->renderSuccess('', [
            'userInfo' => $user,
            'list' => $list
        ]);
    }
    public function registerInfo()
    {
        $user = $this->getUser();
        $where = array('user_id' => $user['user_id']);
        $list = Db::name('register_info')->where($where)->order('id desc')->find();
        return $this->renderSuccess('', [
            'Info' => $list,
        ]);
    }

    public function info_detail()
    {
        $params = $this->request->post();
        $model = new RegisterInfoModel;
        $user = $this->getUser();
        $id = $model->add( $user , $params );
        if( $id == 0 ){
            return $this->renderError( $model->getError() ?:'失败' );
        }
        return $this->renderSuccess('成功',[
            'id' => $id,
        ]);
    }

    //提现
    public function withdrawal()
    {
        $data = $this->request->param();
        $user = $this->getUser();
        $model = new UserWithdrawal();
        $res = $model->add($data,$user);
        if($res){
            return $this->renderSuccess('提现成功');
        }else{
            return $this->renderError($model->getError());
        }
    }

    //提现记录
    public function withdrawal_log()
    {
        $user = $this->getUser();
        $data['user_id'] = $user['user_id'];
        $model = new UserWithdrawal();
        $list = $model->get_list($data);
        return $this->renderSuccess('', [
            'list' => $list,
        ]);
    }

    public function withdrawal_detail()
    {
        $id = $this->request->param('id');
        $model = new UserWithdrawal();
        $info = $model->details($id);
        return $this->renderSuccess('', [
            'info' => $info,
        ]);
    }

    //充值余额
    public function recharge()
    {
        $money = $this->request->param('money');
        if(empty($money) || $money<0){
            return $this->renderError('请输入正确的充值金额');
        }
        $user = $this->getUser();

        //添加充值订单

        $model = new RechargeOrder();
        $res = $model->add($money,$user);
        $order_model = new OrderModel();

        if($res){
            $order = Db::name("recharge_order")->where(array("id"=>$res))->select();
            //$res = $model->pay($order);
            $re = $order_model->onOrderPayment($user, $order, OrderPayTypeEnum::WECHAT, 'app',$types='recharge');
            //$return_Url = urlencode(base_url()."h5/pages/order/myorder/myorder");
            return $this->renderSuccess('',[
                'order' => $order,  // 订单详情
                'pay_info' => $re,
                //'return_Url' => $return_Url
            ]);
        }
    }

    public function bindMobile(){
        $model = new \app\api\model\user\UserWeb;
        if($model->bindMobile($this->getUser(), $this->request->post())){
            return $this->renderSuccess('绑定成功');
        }
        return $this->renderError($model->getError() ?:'绑定失败');
    }

    //获取订单通知
    public function order_message()
    {
        $user = $this->getUser();
        $list = Db::name("order_messages")->alias("om")
            ->field("om.*,ms.status")
            ->join("jjjshop_message_status ms","om.id=ms.mid","left")
            ->where(array('om.user_id'=>$user['user_id']))->order("om.create_time desc")->paginate($this->postData());
        foreach($list as &$v){
            $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
        }
        return $this->renderSuccess('获取成功',['list'=>$list]);
    }

    public function edit_order_message()
    {
        $id = $this->request->param('id');
        Db::name("order_messages")->where(array('id'=>$id))->update(array('is_read'=>1));
        return $this->renderSuccess('修改成功');
    }

    //删除订单通知
    public function del_order_message()
    {
        $id = $this->request->param('id');
        Db::name("order_messages")->where(array('id'=>$id))->delete();
        //Db::name("message_status")->where(array('mid'=>$id))->delete();
        return $this->renderSuccess('删除成功');
    }
    //反馈
    public function feedback()
    {
        $user = $this->getUser();
        $content = $this->request->param('content');
        $data = array(
            'user_id'=>$user['user_id'],
            'content'=>$content,
            'create_time'=>time()
        );
        $res = Db::name("system_feedback")->insertGetId($data);
        if($res){
            return $this->renderSuccess('提交成功');
        }else{
            return $this->renderError('网络似乎开小差了');
        }
    }

    //车主获取未读订单
    public function get_order_status()
    {
        $user = $this->getUser();
        $where[] = ['status','=',1];
        $where[] = ['owner_status','=',-1];
        $order_count = Db::name('car_order')->where($where)->count();
        $message_count = Db::name('message_status')->where(array('user_id'=>$user['user_id']))->count();
        $count = $order_count-$message_count;
        return $this->renderSuccess('获取成功',['count'=>$count]);
    }
    //用户获取未读消息
    public function get_user_message_count()
    {
        $user = $this->getUser();
        $count = Db::name('order_messages')->where(array('user_id'=>$user['user_id'],'is_read'=>0))->count();
        return $this->renderSuccess('获取成功',['count'=>$count]);
    }


}